package com.example.testcache1.utils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

public class ImageLoader {

	private MemoryCache mMemoryCache = new MemoryCache();
	private DiskCache mDiskCache = new DiskCache();

	// 鐢ㄦ潵璁板綍褰撳墠姝ｅ湪涓嬭浇鐨勬墍鏈夌殑浠诲姟
	private Map<String, ImageView> mTask = new HashMap<String, ImageView>();

	private int mLoadingRes;
	private int mLoadFaultRes;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			ImageView img = (ImageView) msg.obj;
			if (msg.what == 1) {
				// 璇锋眰澶辫触鎴栬�鍔犺浇澶辫触鐨勬儏鍐�
				img.setImageResource(mLoadFaultRes);
			} else {
				String path = (String) img.getTag();
				String key = toFileName(path);

				Bitmap bmp = mMemoryCache.get(key);

				if (bmp != null) {
					img.setImageBitmap(bmp);
				}
			}
		};
	};

	public void setLoadingRes(int res) {
		mLoadingRes = res;
	}

	public void setLoadFailureRes(int res) {
		mLoadFaultRes = res;
	}

	public void display(final ImageView img, final String path) {

		final String fileName = toFileName(path);

		img.setTag(path);

		// 鍏堜粠鍐呭瓨缂撳啿涓彇
		Bitmap bmp = mMemoryCache.get(fileName);

		if (bmp != null) {
			img.setImageBitmap(bmp);
			return;
		}

		img.setImageResource(mLoadingRes);

		new Thread() {
			public void run() {

				try {

					Bitmap bmp = mDiskCache.get(fileName);

					if (bmp == null) {

						ImageView task = mTask.get(path);

						if (task == null) {

							// 璇锋眰缃戠粶鏁版嵁
							mTask.put(path, img);

							URL url = new URL(path);

							HttpURLConnection conn = (HttpURLConnection) url.openConnection();

							conn.setRequestMethod("GET");
							conn.setConnectTimeout(25000);
							conn.setReadTimeout(25000);

							int code = conn.getResponseCode();

							if (code == 200) {
								InputStream is = conn.getInputStream();
								mDiskCache.save(fileName, is);
								is.close();

								// 鍦ㄧ嚎绋嬩腑璇诲彇sdcard鐨勭紦瀛�
								// 鍥犱负浠巗dcard涓鍙栧浘鐗囧悓鏍蜂細寮曡捣涓荤嚎绋嬬殑鍗￠】
								bmp = mDiskCache.get(fileName);
							}
						}
					}

					if (bmp != null) {
						mMemoryCache.put(fileName, bmp);

						String tag = (String) img.getTag();

						// 瑙ｅ喅鍥剧墖閿欎綅鐨勯棶棰�
						if (path.equals(tag)) {
							Message.obtain(mHandler, 0, img).sendToTarget();
						}
					} else {
						Message.obtain(mHandler, 1, img).sendToTarget();
					}
				} catch (Exception e) {
					e.printStackTrace();
					Log.i("bm", e.toString());
					Message.obtain(mHandler, 1, img).sendToTarget();
				} finally {
					mTask.remove(path);
				}
			};
		}.start();
	}

	public static String toFileName(String path) {
		return "img_" + path.hashCode() + ".png";
	}
}